#include"date.h"

Date::Date(int year, int month, int day)
	:_year(year)
	, _month(month)
	, _day(day)
{ }

int Date::GetMonthDay(int year, int month)
{
	int a[13] = { 0,31,28,31,30,31,30,31,31,30,31,30,31 };
	if (month == 2 && ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)))
	{
		return 29;
	}
	return a[month];
}

Date::Date(const Date& d)
	:_year(d._year)
	,_month(d._month)
	,_day(d._day)
{ }

Date& Date::operator=(const Date& d)
{
	if (&d != this)
	{
		_year = d._year;
		_month = d._month;
		_day = d._day;
	}
	return *this;
}

Date::~Date()
{
	_year = _month = _day = 0;
}

Date& Date::operator+=(int day)
{
	_day += day;
	int time = GetMonthDay(_year, _month);
	while (_day > time)
	{
		_day -= time;
		_month++;
		if (_month > 12)
		{
			_month -= 12;
			_year++;
		}
		time = GetMonthDay(_year, _month);
	}
	return *this;
}

Date Date::operator+(int day)
{
	Date a = *this;
	a += day;
	return a;
}

Date& Date::operator-=(int day)
{
	_day -= day;
	while (_day <= 0)
	{
		_month--;
		if (_month <= 0)
		{
			_year -= 1;
			_month += 12;
		}
		_day += GetMonthDay(_year, _month);
	}
	return *this;
}

Date Date::operator-(int day)
{
	Date a = *this;
	a -= day;
	return a;
}

Date& Date::operator++()
{
	(*this) += 1;
	return *this;
}

Date Date::operator++(int)
{
	Date a = *this;
	(*this) += 1;
	return a;
}

Date Date::operator--(int)
{
	Date a = *this;
	(*this) -= 1;
	return a;
}

Date& Date::operator--()
{
	(*this) -= 1;
	return *this;
}

bool Date::operator>(const Date& d) const
{
	if (_year > d._year)
	{
		return 1;
	}
	else if (_year == d._year)
	{
		if (_month > d._month)
		{
			return 1;
		}
		else if (_month == d._month)
		{
			if (_day > d._day)
			{
				return 1;
			}
		}
	}
	return 0;
}

bool Date::operator==(const Date& d) const
{
	if (_day == d._day && _month == d._month && _year == d._year)
		return 1;
	else
		return 0;
}

bool Date::operator>= (const Date& d) const
{
	return *this == d || *this > d;
}

bool Date::operator< (const Date& d) const
{
	return !(*this >= d);
}

bool Date::operator<= (const Date & d) const
{
	return !(*this > d);
}

bool Date::operator!= (const Date& d) const
{
	return !(*this == d);
}

int Date::operator-(const Date& date) const
{
	Date max = *this, min = date;
	int flag = (max >= min);
	if (!flag)
	{
		max = date;
		min = *this;
		flag = -1;
	}
	int count = 0;
	while (max > min)
	{
		min++;
		count++;
	}
	return flag * count;
}

std::ostream& operator<<(std::ostream& x,const Date& date)
{
	x << date._year << "/" << date._month << "/" << date._day << std::endl;
	return x;
}

std::istream& operator>>(std::istream& x,Date& date)
{
	x >> date._year >> date._month >> date._day;
	return x;
}
